export class CompareRemakeService {
    constructor(parent) {
        this.parent = parent;
        this.status = {};
    }

    getQuestionInfo() {
        return {
            id: this.parent.Model.questionId, type_code: 'compare', type_name: '比大小', url: this
                .parent.Model.questionId, dispatchOnly: true
        }
    }

    setLocationProperties(data) {
        this.parent.$translator.setData(data);
    }

    getResult() {
        var result = {
            correctAnswer: this.parent.correctAnswer,
            userAnswer: []
        };
        var hasBlank = false;
        $.each(this.parent.viewModel.items(), function (ke, v) {
            result.userAnswer.push(v.userAnswer());
            if (v.userAnswer() == "") {
                hasBlank = true;
            }
        });
        if (!hasBlank) {
            this.parent.answerState = "COMPLETE";
        }

        var correct = true;
        for (var index = 0, len = this.parent.correctAnswer.length; index < len; index++) {
            if (this.parent._mapData(this.parent.correctAnswer[index].answer) != result.userAnswer[index]) {
                correct = false;
                break;
            }
        }
        var returnAnswer = {
            answer: {
                "answer_result": correct,
                "correct_response": this.parent.correctAnswer,
                "user_response": result.userAnswer
            },
            answerState: this.parent.answerState,
            questionId: this.parent.Model.questionId
        };

        this.parent.Logger.debug("CompareRemake getResult " + JSON.stringify(returnAnswer));
        return returnAnswer;
    }

    getStatisticClass() {
        this.parent.Logger.debug("CompareRemake getStatisticClass " + this.parent.statisticClass);
        return this.parent.statisticClass;
    }

    convertDataForStatistics(oriData) {
        var value = oriData.value;
        var onlineNum = 0;
        var correctAnswer,
            item_key = [],
            percent = [],
            stuAnswerStat = [];
        var convertedData = {};

        convertedData["allrightStu"] = [];
        if (value.answers) {
            for (var i = 0, ilen = value.answers.length; i < ilen; i++) {
                if (!$.isArray(value.answers[i])) {
                    break;
                }
                if (value.answers[i].length) {
                    for (var j = 0, jlen = value.answers[i].length; j < jlen; j++) {
                        if (typeof(value.answers[i][j]) != "object") {
                            break;
                        }
                        if (typeof(value.answers[i][j].answer) == "string") {
                            value.answers[i][j].answer = JSON.parse(value.answers[i][j].answer);
                        } else if (typeof(value.answers[i][j].answer) == "object") {
                            value.answers[i][j].answer = value.answers[i][j].answer;
                        } else {
                            break;
                        }

                        $.each(value.answers[i][j].answer.correct_response, function (k, item) {
                            if (!stuAnswerStat[k]) {
                                stuAnswerStat[k] = {
                                    right_userIds: [],
                                    wrong_userIds: [],
                                    unfinished_userIds: value.unfinishedUserIds,
                                    ref_key: (k + 1)
                                };
                                item_key.push(k + 1);
                            }
                            if (value.answers[i][j].answer.correct_response[k].answer ==
                                value.answers[i][j].answer.user_response[k]) {
                                stuAnswerStat[k].right_userIds = stuAnswerStat[k].right_userIds
                                    .concat(value.answers[i][j].userIds);
                            } else {
                                stuAnswerStat[k].wrong_userIds = stuAnswerStat[k].wrong_userIds
                                    .concat(value.answers[i][j].userIds);
                            }
                        });
                        if (value.answers[i][j].answer.answer_result) {
                            convertedData["allrightStu"] = convertedData["allrightStu"].concat(
                                value.answers[i][j].userIds);
                        }
                    }
                } else {
                    $.each(value.correctAnswerTeacher.correct_response, function (k, item) {
                        if (!stuAnswerStat[k]) {
                            stuAnswerStat[k] = {
                                rightNum: 0,
                                right_userIds: [],
                                wrong_userIds: [],
                                unfinished_userIds: value.unfinishedUserIds,
                                ref_key: (k + 1)
                            };
                            item_key.push(k + 1);
                        }
                    });
                    convertedData["allrightStu"] = [];
                }
            }
        }
        $.each(stuAnswerStat, function (k, item) {
            item.rightNum = item.right_userIds.length;
        });
        onlineNum = value.finishedNum + value.unfinishedNum;
        /**计算正确率**/
        for (var ii = 0; ii < stuAnswerStat.length; ii++) {
            percent[ii] = (onlineNum > 0) ? (stuAnswerStat[ii]["rightNum"] / onlineNum).toFixed(2) :
                0;
        }

        convertedData["spend_time"] = value.elapsedTime ? value.elapsedTime : 0;
        convertedData["submit_count"] = onlineNum;
        convertedData["answers"] = value.answers;
        convertedData["item_key"] = item_key;
        convertedData["percent"] = percent;
        convertedData["unfinishedNum"] = value.unfinishedNum;
        convertedData["unfinishedUserIds"] = value.unfinishedUserIds;
        convertedData["stuAnswerStat"] = stuAnswerStat;

        value["convertedData"] = convertedData;
        return oriData;
    }

    /**
     * 显示答案
     * @param answer 需要显示的答案,如果对象为空则显示正确答案
     */
    showAnswer(showAnswerType, commitedAnswer) {
        this.parent.Logger.debug("CompareRemake showAnswer showAnswerType:" + showAnswerType +
            "  commitedAnswer: " + commitedAnswer);
        var answer = null;
        //显示已提交的答案
        if (commitedAnswer) {
            answer = [];
            var committedAnswer = commitedAnswer.answer.user_response;
            if (committedAnswer) {
                for (var index = 0, len = committedAnswer.length; index < len; index++) {
                    answer.push(committedAnswer[index]);
                }
            }
        } else {
            //状态恢复
            this.parent.showAnswerInfo = {
                'hasShow': true,
                'type': showAnswerType
            };

            switch (showAnswerType) {
                //显示正确答案
                case "correct": {
                    answer = [];
                    for (var index = 0, len = this.parent.correctAnswer.length; index < len; index++) {
                        answer.push(this.parent.correctAnswer[index].answer);
                    }
                    break;
                }
                //显示当前学生答案用
                case "user": {
                    answer = [];
                    $.each(this.parent.viewModel.items(), function (ke, v) {
                        answer.push(v.userAnswer());
                    });
                    break;
                }
                //统计使用
                default: {
                    answer = [];
                    for (var index = 0, len = this.parent.correctAnswer.length; index < len; index++) {
                        answer.push(this.parent.correctAnswer[index].answer);
                    }
                    this.parent._toggleInteraction(false);
                    break;
                }
            }
        }
        //把答案赋值给填空
        var self = this;
        $.each(answer, function (key, value) {
            self.parent.viewModel.items()[key].userAnswer(value);
        });
        //检查答案是否正确，并显示相应红绿框
        this.parent._showAnswerCheck();
    }

    showResultHint(option) {
        this.parent.Logger.debug("CompareRemake showResultHint " + option);
        var result = {
            userAnswer: []
        };
        $.each(this.parent.viewModel.items(), function (ke, v) {
            result.userAnswer.push(v.userAnswer());
        });
        var correct = true;
        for (var index = 0, len = this.parent.correctAnswer.length; index < len; index++) {
            if (this.parent._mapData(this.parent.correctAnswer[index].answer) != result.userAnswer[
                    index]) {
                correct = false;
                break;
            }
        }
        //状态恢复
        this.parent.showHintInfo = {
            'hasShow': true,
            'result': correct
        };

        //弹窗提示
        if (this.parent.isApp) {
            this.lockQuestion();
            this.parent.$view.responseTip({
                type: correct ? 'correct' : 'wrong',
                // msg: correct? '太棒了，你全对了！': '很遗憾，未能回答正确',
                msg: correct ? this.parent.$translate('right') : this.parent.$translate(
                    'error'),
                time: option.spendTime,
                auto: 3000,
                text: {
                    minute: this.parent.$translate('minute'),
                    second: this.parent.$translate('second'),
                    tip: this.parent.$translate('tip')
                }
            });
        }
    }

    //将题目重置为未作答状态
    resetQuestion() {
        this.parent.Logger.debug("CompareRemake resetQuesion ");
        //清空所有的作答结果
        $.each(this.parent.viewModel.items(), function (k, v) {
            v.userAnswer('');
        });
        this.parent._resetAnswerCheck();
        // this.parent._toggleInteraction(true);
    }

    _getState() {
        var userAnswers = [];
        var hasBlank = false;
        $.each(this.parent.viewModel.items(), function (ke, v) {
            userAnswers.push(v.userAnswer());
            if (v.userAnswer() == "") {
                hasBlank = true;
            }
        });

        if (!hasBlank) {
            this.parent.answerState = "COMPLETE";
        }

        var state = {
            userAnswers: userAnswers,
            showAnswerInfo: this.parent.showAnswerInfo,
            showHintInfo: this.parent.showHintInfo,
            answerState: this.parent.answerState,
            isLockQuestion: this.parent.toggleSwitch
        };
        this.parent.Logger.debug("CompareRemake getState " + JSON.stringify(state));
        return state;
    }

    getState() {
        this.parent.playerController.startFlow('css_classroom_status_changed', {
            presenterCode: this
                .parent.metaInfo.name
        });
        return this._getState();
    }

    setState(state) {
        this.parent.Logger.debug("CompareRemake setState " + JSON.stringify(state));
        var stateObj = state;
        if (stateObj) {
            for (var i = 0, len = this.parent.viewModel.items().length; i < len; i++) {
                this.parent.viewModel.items()[i].userAnswer(stateObj.userAnswers[i]);
            }

            if (stateObj.showAnswerInfo) {
                if (stateObj.showAnswerInfo.hasShow) {
                    this.showAnswer(stateObj.showAnswerInfo.type);
                }
            }

            if (stateObj.showHintInfo) {
                if (stateObj.showHintInfo.hasShow) {
                    this.showResultHint(stateObj.showHintInfo.result);
                }
            }
            this.parent.answerState = stateObj.answerState;
            this.parent.toggleSwitch = stateObj.isLockQuestion;
        }
    }

    getClassroomStatus() {
        return this._getState();
    }

    setClassroomStatus(status) {
        this.status = status;
        !!this.status && this.setState(status);
        this.parent.$dispatchEvent('css_recover_complete', PresenterEventType.IC_PLAYER_EVENT, {
            presenterCode: this.parent.metaInfo.name
        });
    }

    clearClassroomStatus() {
        this.setClassroomStatus(null);
    }

    startStatistics() {
        this.parent.Logger.debug("CompareRemake startStatistics ");
        //结束答题的时候不清空，退出本题的时候再清空。 修复bug：47603 this.resetQuestion();
        this.parent._setStatisticsViewAttr();
        this.parent._bindStatisticsView();
    }

    //将题目设置为不可作答状态
    lockQuestion() {
        this.parent.Logger.debug("CompareRemake lockQuestion ");
        this.parent._toggleInteraction(false);
    }

    //将题目设置为可作答状态
    unlockQuestion() {
        this.parent.Logger.debug("CompareRemake unlockQuestion ");
        this.parent._toggleInteraction(true);
    }

    //将题目设置为结束作答状态
    finishQuestion() {
        this.parent.Logger.debug("CompareRemake finishQuestion ");
        this.parent._toggleInteraction(true);
    }
}
